package com.java.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.dao.RoleMapper;
import com.java.dao.RolePermissionMapper;
import com.java.model.Permission;
import com.java.model.Result;
import com.java.model.Role;
import com.java.model.RolePermission;
import com.java.service.PermissionService;
import com.java.service.RolePermissionService;
import com.java.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;


    @Override
    public Result toList(Role role) {
        PageHelper.startPage(role.getPageNum(), role.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<Role> roles = roleMapper.toList(role);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Role get(int id) {
        return roleMapper.get(id);
    }

    @Override
    public Result save(Role role) {
        roleMapper.save(role);
        return Result.success();
    }

    @Override
    public Result modify(Role role) {
        roleMapper.modify(role);
        return Result.success();
    }

    @Override
    public Result remove(int[] ids) {
        for (int id : ids) {
            roleMapper.remove(id);
        }
        return Result.success();
    }

    @Override
    public Result listPermission(int roleId) {
        // 查询所有权限用于显示列表
        Result result = permissionService.toList(new Permission());
        if (!result.getCode().equals("0")) {
            return result;
        }

        // 2.查询操作的角色有的权限
        List<RolePermission> rolePermissionList = rolePermissionMapper.list(roleId);
        List<Integer> permissionIdList = new ArrayList<>();
        if (rolePermissionList != null && rolePermissionList.size() > 0) {
            for (RolePermission rolePermission : rolePermissionList) {
                permissionIdList.add(rolePermission.getPermissionId());
            }
        }

        // 3.遍历所有权限判断操作角色是否有该权限，如果有则将checked设置为true， 如果没有设置成false
        List<Permission> permissionsList = (List<Permission>) result.getData();
        if (permissionsList != null && permissionsList.size() > 0) {
            for (Permission permission : permissionsList) {
                if (permissionIdList.contains(permission.getId())) {
                    permission.setChecked(true);
                } else {
                    permission.setChecked(false);
                }
            }
        }
        return result;
    }
}
